package com.finalab.yueqiu.controller.auth;

import com.finalab.yueqiu.constant.ResponseCode;
import com.finalab.yueqiu.service.auth.AuthServiceImpl;
import com.finalab.yueqiu.util.RandomCodeUtil;
import com.finalab.yueqiu.util.ResponseUtil;
import com.qcloud.cos.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;


/**
 * @author 莉安
 */
@Controller
public class AuthController {

    @Autowired
    AuthServiceImpl authServiceImpl;

    private static final int PHONE_LENGTH = 11;
    @RequestMapping(value = "/phone/auth", method = RequestMethod.POST)
    public void authPhone(@RequestParam String phone, PrintWriter out,
                          HttpSession session){
        if(StringUtils.isNullOrEmpty(phone) || phone.length() != PHONE_LENGTH){
            ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL.getValue());
            return;
        }
        String param = RandomCodeUtil.getCode();
        int code = 0;
//        int code = authServiceImpl.authPhone(phone, param);
//        if(code == ResponseCode.REQUEST_SUCCESSED.getValue()){
            session.setAttribute("phone", phone);
//        }
            ResponseUtil.responseCode(out, code);
    }

    @RequestMapping(value = "/phone/succeed")
    public void phoneSucceed(HttpSession session, PrintWriter out,
                             @RequestParam String param){
        String phone = (String) session.getAttribute("phone");
        if(phone == null || param == null){
            ResponseUtil.responseCode(out, ResponseCode.USER_NOT_AUTH.getValue());
            return;
        }
            int code = authServiceImpl.phoneSuccess(phone, param);
        ResponseUtil.responseCode(out, code);
    }

}
